package com.runen.infinitemovement.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.runen.infinitemovement.R;
import com.runen.infinitemovement.adapter.CheckTeamAdapter;
import com.runen.infinitemovement.base.BaseActivity;
import com.runen.infinitemovement.model.api.CompanyAPI;
import com.runen.infinitemovement.model.api.UserAPI;
import com.runen.infinitemovement.model.base.BaseResponseEntity;
import com.runen.infinitemovement.model.entity.EventBusEntity;
import com.runen.infinitemovement.model.entity.TeamListEntity;
import com.runen.infinitemovement.model.enums.ActivityCompat;
import com.runen.infinitemovement.tool.ActivityUtils;
import com.runen.infinitemovement.tool.AppUtils;
import com.runen.infinitemovement.widget.popupwind.CommonDialog;
import com.runen.rxnetlibrary.net.callback.BaseResultCallback;
import com.runen.rxnetlibrary.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class CheckTeamActivity extends BaseActivity {
    @BindView(R.id.top_btn_left)
    Button topBtnLeft;
    @BindView(R.id.top_tv_right)
    TextView topTvRight;
    @BindView(R.id.edt_input_search)
    EditText edtInputSearch;
    @BindView(R.id.rv_team_list)
    RecyclerView rvTeamList;
    @BindView(R.id.top_title)
    TextView top_title;
    @BindView(R.id.tv_null)
    TextView tvNull;
    private String companyId;
    private CheckTeamAdapter checkTeamAdapter;
    private String edtString = "";
    private int type;
    private boolean isTeamGroup;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_check_team;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        ButterKnife.bind(this);
        companyId = getIntent().getStringExtra(ActivityCompat.TEAM_GROUP_ID);
        type = getIntent().getIntExtra("type", 0);
        LinearLayoutManager layoutManager = new GridLayoutManager(this, 3);
        rvTeamList.setLayoutManager(layoutManager);

        isTeamGroup = getIntent().getBooleanExtra(ActivityCompat.TeamGroup, false);
        //军团管理跳转过来 隐藏创建团队
        if (isTeamGroup) {
            topTvRight.setVisibility(View.GONE);
            top_title.setText("我的军团");
        }
        checkTeamAdapter = new CheckTeamAdapter(this, isTeamGroup);
        rvTeamList.setAdapter(checkTeamAdapter);

        edtInputSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {//修改回车键功能
                    //代码
                    edtString = v.getText().toString().trim();
                    initData();
                }
                return false;
            }
        });
        checkTeamAdapter.setOnJoinClickListener(new CheckTeamAdapter.OnJoinClickListener() {
            @Override
            public void onClick(String teamId, String teamName) {
                CommonDialog.getInstance(CheckTeamActivity.this, "", teamName, "取消", "确定", 0).setOnClickListener(new CommonDialog.OnClickListener() {
                    @Override
                    public void onSendListener() {

                    }

                    @Override
                    public void onDismiss() {
                        onSure(teamId);
                    }
                });
            }
        });
        if (isTeamGroup) {
            checkTeamAdapter.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                    Intent intent = new Intent(CheckTeamActivity.this, MyTeamActivity.class);
                    intent.putExtra(ActivityCompat.TEAM_ID, checkTeamAdapter.getData().get(position).teamId);
                    intent.putExtra(ActivityCompat.TeamGroup, true);
                    startActivity(intent);
                }
            });
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    private void onSure(String teamId) {
        JSONObject object = new JSONObject();
        try {
            object.put("tenantId", teamId);
            object.put("topTenantId", companyId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new UserAPI().submitBranch(object.toString(), type, new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {
                if (response.getCode() == 0) {
                    if (type == 1) {
                        EventBus.getDefault().post(new EventBusEntity(102));
                        EventBus.getDefault().post(new EventBusEntity(100));
                        EventBus.getDefault().post(new EventBusEntity(104));
                        ActivityUtils.getInstance().finishAllActivityExcept(MainActivity.class);
                    } else {
                        EventBus.getDefault().post(new EventBusEntity(4));
//                        startActivity(new Intent(CheckTeamActivity.this, MainActivity.class));
                        AppUtils.jumpToMain(CheckTeamActivity.this);
                    }
                    finish();
                } else {
                    ToastUtils.showShort(response.getMessage());
                }
            }
        });
    }


    private void initData() {
        String string = "?selectDate=%s&topTenantId=%s";
        showDialog();
        new CompanyAPI().getTeamList(String.format(string, edtString, companyId), new BaseResultCallback<TeamListEntity>() {
            @Override
            public void onResponse(TeamListEntity response) {
                dismissDialog();
                if (response.code == 0) {
                    if (response.data != null && response.data.size() > 0) {
                        rvTeamList.setVisibility(View.VISIBLE);
                        tvNull.setVisibility(View.GONE);
                        checkTeamAdapter.setNewInstance(response.data);
                    } else {
                        rvTeamList.setVisibility(View.GONE);
                        tvNull.setVisibility(View.VISIBLE);
                    }
                }
            }

            @Override
            public void onError(Throwable e, String body) {
                super.onError(e, body);
                dismissDialog();
            }
        });
    }

    @OnClick({R.id.top_btn_left, R.id.top_tv_right})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.top_btn_left:
                finish();
                break;
            case R.id.top_tv_right:
                Intent intent = new Intent(this, CrateCorpsActivity.class);
                intent.putExtra("parentId", companyId);
                startActivity(intent);
                break;
        }
    }
}